OCAML = ocamlopt
OCAMLC = ocamlc -custom -g
INCDIRS=$(shell ocamlfind printconf stdlib)
CPPFLAGS = $(patsubst %, -I %/$(BDIR), $(INCDIRS) )
CFLAGS= -Wall -g -fPIC
CPP = g++ $(CFLAGS) $(CPPFLAGS)
CC = gcc $(CFLAGS)
all: o

LIB = unix.cmxa bigarray.cmxa dbm.cmxa \
      Glob.cmx Ocaml_dbm.cmx Db_dir.cmx

ROOT_LINK=ttree_decl_$(TA_DECL)_root_link

#TARGETS = $(ROOT_LINK).o fill_struct.o ttree_creation.o \
#	  c_fill_record.o  Ocaml_dbm.cmx Db_dir.cmx $(TA_DECL).cmx \
#	  ocaml_creation.cmx

TARGETS = $(ROOT_LINK).o ttree_decl_stubs.o c_fill_record.o \
	ttree_creation.o $(TA_DECL).cmx $(TA_DECL)_obj.cmx $(MOD_ID)_inc.cmx 

# for ocamlbuild
CLIBLST=lib$(TA_DECL).clib
clib:
	echo > $(CLIBLST)
	echo $(ROOT_LINK).o >> $(CLIBLST)
	echo ttree_decl_stubs.o >> $(CLIBLST)
	echo c_fill_record.o >> $(CLIBLST)
	echo ttree_creation.o >> $(CLIBLST)
	echo open OKAHEP >> $(MOD_ID).ml
	cat $(MOD_ID)_inc.ml >> $(MOD_ID).ml

PROGFILL = fill.cmx

ifeq ($(MAKECMDGOALS),o)
    TARGETS := $(patsubst %.cmx, %.cmo, $(TARGETS))
    PROGFILL := $(patsubst %.cmx, %.cmo, $(PROGFILL))
    LIB := $(patsubst %.cmxa, %.cma, $(LIB))
    LIB := $(patsubst %.cmx, %.cmo, $(LIB))
    OCAML := $(OCAMLC)
endif

OCAMLFLAGS=-I $(INST_DIR_COMMON)

%.cmx: %.ml
	$(OCAML) $(OCAMLFLAGS) $< -c -o $@

%.cmo: %.ml
	$(OCAMLC) $(OCAMLFLAGS) $< -c -o $@

$(TA_DECL).cmo: $(TA_DECL).cmi $(TA_DECL).ml
	$(OCAMLC) $(OCAMLFLAGS) $(TA_DECL).ml -c -o $@
$(TA_DECL).cmx: $(TA_DECL).cmi $(TA_DECL).ml
	$(OCAML) $(OCAMLFLAGS) $(TA_DECL).ml -c -o $@

$(TA_DECL).cmi: $(TA_DECL).mli
	$(OCAML) $(TA_DECL).mli -o $(TA_DECL).cmi

$(TA_DECL)_obj.cmx: $(TA_DECL)_obj.ml
	$(OCAML) $(OCAMLFLAGS) $(TA_DECL)_obj.ml -c -o $@
$(TA_DECL)_obj.cmo: $(TA_DECL)_obj.ml
	$(OCAMLC) $(OCAMLFLAGS) $(TA_DECL)_obj.ml -c -o $@

$(TA_DECL)_obj.ml:
	bash gen_class.sh > $(TA_DECL)_obj.ml

o: lib $(TA_DECL)_stubs.cpp $(TARGETS) $(PROGFILL)
	$(OCAML) $(OCAMLFLAGS) -g -ccopt "`root-config --cflags --glibs`" \
	$(LIB) $(TARGETS) $(PROGFILL) -o convert

lib: $(TARGETS)
	ocamlmklib -o $(MOD_ID) $(TARGETS)

$(TA_DECL)_stubs.cpp $(TA_DECL).ml: $(TA_DECL).idl
	camlidl -no-include $(TA_DECL).idl
	mv $(TA_DECL)_stubs.c $(TA_DECL)_stubs.cpp

ttree_decl_stubs.o: ttree_decl_stubs.cpp $(TA_DECL)_stubs.cpp
	$(CPP) `root-config --cflags` ttree_decl_stubs.cpp -c -o ttree_decl_stubs.o

ttree_creation.o:  ttree_creation.cpp
	$(CPP) `root-config --cflags` ttree_creation.cpp -c -o ttree_creation.o

c_fill_record.o: c_fill_record.cpp
	$(CPP) `root-config --cflags` c_fill_record.cpp -c -o c_fill_record.o

$(ROOT_LINK).cpp:
	rootcint -f $(ROOT_LINK).cpp -c ttree_declaration.h ttree_declLinkDef.h

$(ROOT_LINK).o: $(ROOT_LINK).cpp ttree_declaration.h
	$(CPP)  `root-config --cflags ` $(ROOT_LINK).cpp -c -o $(ROOT_LINK).o


TTreePlayer_new: TTreePlayer_new.cxx
	$(CPP) `root-config --cflags --glibs` TTreePlayer_new.cxx -Wall -o TTreePlayer_new


clean:
	rm -f *.cmx *.cmo *.cmi *.cma *.o fill
